package cn.com.edaily.auth.facade;

import cn.com.edaily.auth.dto.UserDTO;
import cn.com.edaily.auth.enumeration.RegisterResultEnum;
import cn.com.edaily.auth.enumeration.UserStatusEnum;
import cn.com.edaily.auth.help.AuthHelper;
import cn.com.edaily.auth.request.LoginRequestDTO;
import cn.com.edaily.auth.request.RegisterRequestDTO;
import cn.com.edaily.auth.service.AuthService;
import cn.com.edaily.auth.utils.RsaKeyFactory;
import cn.com.edaily.auth.utils.RsaUtil;
import cn.com.edaily.auth.utils.UuidUtil;
import cn.com.edaily.common.Response;
import com.alibaba.nacos.common.util.Md5Utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;


/**
 * <pre>类名: AuthFacade</pre>
 * <pre>描述: 认证facade</pre>
 * <pre>版权: web_chen@163.com</pre>
 * <pre>日期: 2020/1/30 15:28</pre>
 * <pre>作者: chenwb</pre>
 */

@Service
public class AuthFacade {

	@Autowired
	private AuthService authService;

	@Autowired
	private AuthHelper authHelper;

	/**
	 * @param requestDTO
	 * @return Response<?>
	 * @Description: 注册
	 * @author chenwb
	 * @date 2020/1/30 15:29
	 */
	public Response<?> register(RegisterRequestDTO requestDTO) {
		//获取私钥，解密，获取用户名密码
		String password = authHelper.decrypt(requestDTO.getPassword(), requestDTO.getKeyIndex());
		//校验信息（是否重复）

		if (authService.checkUserDuplicate(requestDTO.getUsername())) {
			return Response.error(RegisterResultEnum.EXSIST.getCode(), RegisterResultEnum.EXSIST.getText(), "");
		}

		//准备注册信息
		String salt = UuidUtil.generateUuid();
		String md5Password = new Md5Hash(password, salt).toString();

		UserDTO userDTO = new UserDTO(UuidUtil.generateUuid(), requestDTO.getUsername(), md5Password, salt,
				requestDTO.getUsername(), UserStatusEnum.VALID.getCode(), new Date(), new Date());
		authService.saveUser(userDTO);
		//返回注册结果
		return Response.success(RegisterResultEnum.SUCCESS.getCode(), RegisterResultEnum.SUCCESS.getText(), "");
	}

	/**
	 * @Description: 用户登录
	 * @author chenwb
	 * @date 2020/1/31 17:07
	 * @param requestDTO
	 * @return 输出参数
	 */
	public void Login(LoginRequestDTO requestDTO) {
		String password = authHelper.decrypt(requestDTO.getPassword(), requestDTO.getKeyIndex());
		UsernamePasswordToken token = new UsernamePasswordToken(requestDTO.getUsername(), password);
		Subject subject = SecurityUtils.getSubject();
		subject.login(token);
	}
}

